<template>
  <div class="home">
    <!-- 智能物品匹配系统 -->
    <el-card class="ai-matcher-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="title-wrapper">
            <el-icon class="ai-icon"><Connection /></el-icon>
            <span class="section-title">智能物品匹配系统</span>
          </div>
          <el-tag type="success" effect="dark" class="ai-tag">AI驱动</el-tag>
        </div>
      </template>

      <div class="matcher-content">
        <div class="input-section">
          <div class="text-input">
            <h3>描述您的物品</h3>
            <el-input
              v-model="itemDescription"
              type="textarea"
              :rows="3"
              placeholder="请详细描述物品的外观、颜色、品牌、特征等（例如：一个黑色Nike背包，侧面有小口袋，内有一本红色笔记本）"
              @input="handleInputChange"
            />

            <div class="quick-attributes">
              <h4>快速添加特征：</h4>
              <div class="attribute-tags">
                <el-tag @click="addAttribute('黑色')" class="clickable-tag"
                  >黑色</el-tag
                >
                <el-tag @click="addAttribute('白色')" class="clickable-tag"
                  >白色</el-tag
                >
                <el-tag @click="addAttribute('红色')" class="clickable-tag"
                  >红色</el-tag
                >
                <el-tag @click="addAttribute('蓝色')" class="clickable-tag"
                  >蓝色</el-tag
                >
                <el-tag @click="addAttribute('灰色')" class="clickable-tag"
                  >灰色</el-tag
                >
                <el-tag @click="addAttribute('绿色')" class="clickable-tag"
                  >绿色</el-tag
                >
                <el-tag @click="addAttribute('黄色')" class="clickable-tag"
                  >黄色</el-tag
                >
                <el-tag @click="addAttribute('粉色')" class="clickable-tag"
                  >粉色</el-tag
                >
                <el-tag @click="addAttribute('紫色')" class="clickable-tag"
                  >紫色</el-tag
                >
                <el-tag @click="addAttribute('金色')" class="clickable-tag"
                  >金色</el-tag
                >
                <el-tag @click="addAttribute('银色')" class="clickable-tag"
                  >银色</el-tag
                >

                <el-tag @click="addAttribute('金属材质')" class="clickable-tag"
                  >金属材质</el-tag
                >
                <el-tag @click="addAttribute('皮质')" class="clickable-tag"
                  >皮质</el-tag
                >
                <el-tag @click="addAttribute('塑料')" class="clickable-tag"
                  >塑料</el-tag
                >
                <el-tag @click="addAttribute('布质')" class="clickable-tag"
                  >布质</el-tag
                >
                <el-tag @click="addAttribute('木质')" class="clickable-tag"
                  >木质</el-tag
                >
                <el-tag @click="addAttribute('玻璃')" class="clickable-tag"
                  >玻璃</el-tag
                >
                <el-tag @click="addAttribute('橡胶')" class="clickable-tag"
                  >橡胶</el-tag
                >

                <el-tag @click="addAttribute('方形')" class="clickable-tag"
                  >方形</el-tag
                >
                <el-tag @click="addAttribute('圆形')" class="clickable-tag"
                  >圆形</el-tag
                >
                <el-tag @click="addAttribute('长方形')" class="clickable-tag"
                  >长方形</el-tag
                >
                <el-tag @click="addAttribute('三角形')" class="clickable-tag"
                  >三角形</el-tag
                >
                <el-tag @click="addAttribute('椭圆形')" class="clickable-tag"
                  >椭圆形</el-tag
                >

                <el-tag @click="addAttribute('大型')" class="clickable-tag"
                  >大型</el-tag
                >
                <el-tag @click="addAttribute('中型')" class="clickable-tag"
                  >中型</el-tag
                >
                <el-tag @click="addAttribute('小型')" class="clickable-tag"
                  >小型</el-tag
                >
                <el-tag @click="addAttribute('轻便')" class="clickable-tag"
                  >轻便</el-tag
                >
                <el-tag @click="addAttribute('厚重')" class="clickable-tag"
                  >厚重</el-tag
                >

                <el-tag @click="addAttribute('带logo')" class="clickable-tag"
                  >带logo</el-tag
                >
                <el-tag @click="addAttribute('有刮痕')" class="clickable-tag"
                  >有刮痕</el-tag
                >
                <el-tag @click="addAttribute('新旧程度')" class="clickable-tag"
                  >新旧程度</el-tag
                >
                <el-tag @click="addAttribute('有图案')" class="clickable-tag"
                  >有图案</el-tag
                >
                <el-tag @click="addAttribute('防水')" class="clickable-tag"
                  >防水</el-tag
                >
                <el-tag @click="addAttribute('多功能')" class="clickable-tag"
                  >多功能</el-tag
                >
                <el-tag @click="addAttribute('带锁')" class="clickable-tag"
                  >带锁</el-tag
                >
                <el-tag @click="addAttribute('可折叠')" class="clickable-tag"
                  >可折叠</el-tag
                >

                <el-tag @click="addAttribute('电子产品')" class="clickable-tag"
                  >电子产品</el-tag
                >
                <el-tag @click="addAttribute('学习用品')" class="clickable-tag"
                  >学习用品</el-tag
                >
                <el-tag @click="addAttribute('生活用品')" class="clickable-tag"
                  >生活用品</el-tag
                >
                <el-tag @click="addAttribute('运动装备')" class="clickable-tag"
                  >运动装备</el-tag
                >
                <el-tag @click="addAttribute('首饰饰品')" class="clickable-tag"
                  >首饰饰品</el-tag
                >
              </div>
            </div>
          </div>

          <div class="image-input">
            <h3>上传物品图片</h3>
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :on-change="handleImageChange"
              :on-remove="handleImageRemove"
              :before-upload="beforeImageUpload"
              :limit="3"
              :file-list="fileList"
              list-type="picture-card"
              multiple
            >
              <template #default>
                <el-icon><Plus /></el-icon>
              </template>
              <template #file="{ file }">
                <img class="preview-image" :src="file.url" alt="物品图片" />
              </template>
            </el-upload>
            <p v-if="imageUploadError" class="upload-error">
              {{ imageUploadError }}
            </p>
            <p class="upload-tip">最多上传3张图片，提高匹配精度（选填）</p>
          </div>
        </div>

        <div class="action-section">
          <div class="filter-options">
            <span class="filter-label">匹配时间范围：</span>
            <el-select
              v-model="searchTimeRange"
              size="default"
              style="width: 120px"
            >
              <el-option label="最近7天" :value="7" />
              <el-option label="最近30天" :value="30" />
              <el-option label="最近90天" :value="90" />
              <el-option label="不限时间" :value="0" />
            </el-select>
          </div>

          <div class="action-buttons">
            <el-button
              type="primary"
              :icon="Search"
              :disabled="!itemDescription.trim()"
              @click="findMatches"
              :loading="searching"
            >
              开始智能匹配
            </el-button>
            <el-button @click="resetForm" :icon="Delete">重置</el-button>
          </div>
        </div>

        <!-- 匹配结果显示 -->
        <div v-if="searching" class="loading-container">
          <el-skeleton :rows="3" animated />
          <div class="loading-text">
            <el-icon class="is-loading"><Loading /></el-icon>
            正在进行智能匹配，请稍候...
          </div>
        </div>

        <div v-else-if="matchResults.length > 0" class="match-results">
          <div class="results-header">
            <el-icon class="match-icon"><TrendCharts /></el-icon>
            <h3>匹配结果（相似度排序）</h3>
          </div>

          <div v-if="matchResults.length > 0" class="ai-analysis-panel">
            <h4>AI分析结果</h4>
            <div class="analysis-content">
              <div class="analysis-item">
                <span class="label">匹配关键词:</span>
                <el-tag
                  v-for="keyword in aiAnalysis.keywords"
                  :key="keyword"
                  size="small"
                  effect="plain"
                  class="keyword-tag"
                >
                  {{ keyword }}
                </el-tag>
              </div>
              <div class="analysis-item">
                <!-- <span class="label">物品分类:</span> -->
                <el-tag
                  v-for="category in aiAnalysis.categories"
                  :key="category"
                  type="success"
                  size="small"
                  effect="dark"
                >
                  {{ category }}
                </el-tag>
              </div>
            </div>
          </div>

          <el-row :gutter="20">
            <el-col
              :xs="24"
              :sm="12"
              :md="8"
              v-for="(item, index) in matchResults"
              :key="index"
            >
              <el-card
                class="match-card"
                :body-style="{ padding: '0px' }"
                shadow="hover"
              >
                <div class="match-banner" :class="item.type">
                  <span class="match-type">{{
                    item.type === "lost" ? "寻物启事" : "失物招领"
                  }}</span>
                  <div class="match-score">
                    <el-progress
                      type="dashboard"
                      :percentage="item.score"
                      :color="getScoreColor(item.score)"
                      :width="40"
                      :stroke-width="6"
                    />
                    <span class="score-text">{{ item.score }}% 匹配</span>
                  </div>
                </div>

                <div class="match-content">
                  <el-image
                    :src="
                      item.images && item.images.length > 0
                        ? item.images[0]
                        : defaultImage
                    "
                    fit="cover"
                    class="match-image"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>

                  <div class="match-info">
                    <h4 class="match-name">{{ item.name }}</h4>
                    <p class="match-location">
                      <el-tag size="small">{{ item.location }}</el-tag>
                    </p>
                    <p class="match-highlights">
                      <span class="highlights-label">匹配点：</span>
                      <el-tag
                        v-for="(highlight, i) in item.highlights"
                        :key="i"
                        size="small"
                        type="info"
                        effect="plain"
                        class="highlight-tag"
                      >
                        {{ highlight }}
                      </el-tag>
                    </p>
                    <el-button
                      type="primary"
                      size="small"
                      @click="viewDetail(item)"
                      text
                    >
                      查看详情
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <div v-else-if="searched" class="no-results">
          <el-empty description="未找到匹配物品" :image-size="100">
            <template #description>
              <p>未找到匹配物品，建议：</p>
              <ul>
                <li>添加更多物品特征描述</li>
                <li>尝试使用不同的关键词</li>
                <li>上传清晰的物品图片</li>
              </ul>
            </template>
            <el-button type="primary" @click="$router.push('/publish')"
              >发布寻物/招领信息</el-button
            >
          </el-empty>
        </div>
      </div>
    </el-card>

    <!-- 最新信息展示 -->
    <div class="latest-info">
      <div class="dual-cards-container">
        <!-- 寻物启事卡片 -->
        <el-card class="dual-card lost-card" v-loading="loadingLost">
          <template #header>
            <div class="card-header">
              <span class="section-title">最新寻物启事</span>
              <el-button class="button" text @click="$router.push('/lost')">
                查看更多
              </el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12" v-for="item in lostItems" :key="item.id">
              <div
                class="lost-item-card"
                @click="$router.push(`/lost/${item.id}`)"
              >
                <el-image
                  :src="item.images?.[0] || ''"
                  fit="cover"
                  class="item-image"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                      <span>图片暂无</span>
                    </div>
                  </template>
                </el-image>
                <div class="item-content">
                  <h4>{{ item.name }}</h4>
                  <p class="item-details">
                    <el-tag size="small">{{ item.location }}</el-tag>
                  </p>
                  <p class="item-time">{{ formatTime(item.time) }}</p>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 失物招领卡片 -->
        <el-card class="dual-card found-card" v-loading="loadingFound">
          <template #header>
            <div class="card-header">
              <span class="section-title">最新失物招领</span>
              <el-button class="button" text @click="$router.push('/found')">
                查看更多
              </el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12" v-for="item in foundItems" :key="item.id">
              <div
                class="found-item-card"
                @click="$router.push(`/found/${item.id}`)"
              >
                <el-image
                  :src="item.images?.[0] || ''"
                  fit="cover"
                  class="item-image"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                      <span>图片暂无</span>
                    </div>
                  </template>
                </el-image>
                <div class="item-content">
                  <h4>{{ item.name }}</h4>
                  <p class="item-details">
                    <el-tag size="small" type="success">{{
                      item.location
                    }}</el-tag>
                  </p>
                  <p class="item-time">{{ formatTime(item.time) }}</p>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </div>

    <!-- 使用指南 -->
    <div class="guide-section">
      <h2>使用指南</h2>
      <el-row :gutter="20">
        <el-col :span="6" v-for="guide in guides" :key="guide.title">
          <el-card class="guide-card" shadow="hover">
            <el-icon :size="40" class="guide-icon">
              <component :is="guide.icon" />
            </el-icon>
            <h3>{{ guide.title }}</h3>
            <p>{{ guide.description }}</p>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据概览 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="overview-card" shadow="hover">
            <div class="overview-content">
              <div class="overview-icon success">
                <el-icon :size="40"><Check /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-title">今日找回</div>
                <div class="overview-number">12</div>
                <div class="overview-trend">
                  较昨日 <span class="up">+2</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="overview-card" shadow="hover">
            <div class="overview-content">
              <div class="overview-icon primary">
                <el-icon :size="40"><Document /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-title">在线信息</div>
                <div class="overview-number">256</div>
                <div class="overview-trend">
                  本周发布 <span class="emphasis">89</span> 条
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="overview-card" shadow="hover">
            <div class="overview-content">
              <div class="overview-icon warning">
                <el-icon :size="40"><Timer /></el-icon>
              </div>
              <div class="overview-info">
                <div class="overview-title">处理中</div>
                <div class="overview-number">45</div>
                <div class="overview-trend">
                  平均处理时间 <span class="emphasis">2.5</span> 天
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据概览部分之后添加拾物英雄榜 -->
    <div class="hero-section">
      <HeroList />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import api from "@/utils/api";
import { DEFAULT_IMAGE } from "@/constants";
import {
  Search,
  Edit,
  Bell,
  User,
  Upload,
  Check,
  Location,
  Timer,
  Document,
  QuestionFilled,
  InfoFilled,
  Warning,
  Picture,
  Connection,
  TrendCharts,
  Plus,
  Delete,
  Loading,
} from "@element-plus/icons-vue";
import HeroList from "@/components/HeroList.vue"; // 导入新创建的英雄榜组件

export default {
  name: "HomePage",
  components: {
    Search,
    Edit,
    Bell,
    User,
    Upload,
    Check,
    Location,
    Timer,
    Document,
    QuestionFilled,
    InfoFilled,
    Warning,
    Picture,
    Connection,
    TrendCharts,
    Plus,
    Delete,
    HeroList, // 注册英雄榜组件
    Loading, // 注册Loading组件
  },
  setup() {
    // 添加 uploadRef 定义
    const uploadRef = ref(null);

    // 失物招领和寻物启事数据
    const lostItems = ref([]);
    const foundItems = ref([]);
    const loadingLost = ref(false);
    const loadingFound = ref(false);

    // 智能匹配系统相关变量
    const itemDescription = ref("");
    const selectedImages = ref([]);
    const fileList = ref([]);
    const matchResults = ref([]);
    const searching = ref(false);
    const searched = ref(false);
    const searchTimeRange = ref(30);
    const aiAnalysis = ref(null);
    const imageUploadError = ref("");

    // 获取最新寻物启事
    const fetchLatestLostItems = async () => {
      loadingLost.value = true;
      try {
        const response = await api.get("/items/latest", {
          params: { type: "lost", limit: 2 },
        });
        if (response.data.code === 200) {
          lostItems.value = response.data.data.list;
        }
      } catch (error) {
        console.error("获取最新寻物启事失败:", error);
        ElMessage.error("获取最新寻物启事失败，请稍后重试");
      } finally {
        loadingLost.value = false;
      }
    };

    // 获取最新失物招领
    const fetchLatestFoundItems = async () => {
      loadingFound.value = true;
      try {
        const response = await api.get("/items/latest", {
          params: { type: "found", limit: 2 },
        });
        if (response.data.code === 200) {
          foundItems.value = response.data.data.list;
        }
      } catch (error) {
        console.error("获取最新失物招领失败:", error);
        ElMessage.error("获取最新失物招领失败，请稍后重试");
      } finally {
        loadingFound.value = false;
      }
    };

    // 格式化时间
    const formatTime = (time) => {
      if (!time) return "";
      // 简单格式化，可以根据需要修改
      const date = new Date(time);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    };

    onMounted(() => {
      fetchLatestLostItems();
      fetchLatestFoundItems();
    });

    // 引导项数据保持不变
    const guides = [
      {
        title: "我丢了东西",
        description: "发布寻物启事，让拾到者联系你",
        icon: "Search",
        route: "/publish?type=lost",
      },
      {
        title: "我拾到东西",
        description: "发布招领信息，帮助失主找回",
        icon: "Collection",
        route: "/publish?type=found",
      },
      {
        title: "寻找失物",
        description: "浏览失物招领信息，看是否有你的物品",
        icon: "View",
        route: "/found",
      },
      {
        title: "使用指南",
        description: "查看平台使用教程和常见问题解答",
        icon: "Document",
        route: "/guide",
      },
    ];

    // 添加特征到描述文本框
    const addAttribute = (attr) => {
      console.log("添加特征:", attr); // 添加日志以便调试

      // 如果描述为空，直接添加特征
      if (!itemDescription.value.trim()) {
        itemDescription.value = attr;
        return;
      }

      // 判断末尾是否有标点或空格
      const lastChar = itemDescription.value.charAt(
        itemDescription.value.length - 1
      );
      if (
        lastChar === "，" ||
        lastChar === "。" ||
        lastChar === "、" ||
        lastChar === " "
      ) {
        itemDescription.value += attr;
      } else {
        // 没有则添加一个顿号和特征
        itemDescription.value += "、" + attr;
      }
    };

    // 处理输入变化
    const handleInputChange = () => {
      // 可以在这里添加实时处理逻辑，如关键词分析
      // 留空作为将来扩展
    };

    // 处理图片选择
    const handleImageChange = (file, files) => {
      imageUploadError.value = "";

      // 更新已选择的图片数组
      if (!selectedImages.value.some((img) => img.uid === file.raw.uid)) {
        selectedImages.value.push(file.raw);
      }

      // 更新文件列表
      fileList.value = files;
    };

    // 处理图片移除
    const handleImageRemove = (file) => {
      // 从选中图片数组中移除
      selectedImages.value = selectedImages.value.filter(
        (img) => img.uid !== file.raw.uid
      );
    };

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isValidFormat = ["image/jpeg", "image/png", "image/jpg"].includes(
        file.type
      );
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isValidFormat) {
        imageUploadError.value = "只能上传JPG/PNG格式的图片!";
        return false;
      }

      if (!isLt2M) {
        imageUploadError.value = "图片大小不能超过2MB!";
        return false;
      }

      return true;
    };

    // 上传多张图片到服务器
    const uploadImages = async (files) => {
      if (!files || files.length === 0) return [];

      try {
        const uploadPromises = files.map(async (file) => {
          const formData = new FormData();
          formData.append("image", file);

          const response = await api.post("/item/upload-image", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });

          if (response.data.code === 200) {
            return response.data.data.imageUrl;
          } else {
            throw new Error(response.data.message || "上传失败");
          }
        });

        return await Promise.all(uploadPromises);
      } catch (error) {
        console.error("图片上传失败:", error);
        imageUploadError.value = "部分图片上传失败，请重试";
        return [];
      }
    };

    // 开始匹配
    const findMatches = async () => {
      if (!itemDescription.value.trim()) return;

      searching.value = true;
      searched.value = true;

      try {
        // 如果有图片，先上传图片
        let imageUrls = [];
        if (selectedImages.value.length > 0) {
          imageUrls = await uploadImages(selectedImages.value);
        }

        // 构建请求数据
        const requestData = {
          description: itemDescription.value,
          itemType: "all",
          timeRange: searchTimeRange.value,
          imageUrls: imageUrls, // 修改为图片URL数组
        };

        // 发送匹配请求
        const response = await api.post("/items/match", requestData);

        if (response.data.code === 200) {
          matchResults.value = response.data.data.matches;
          // 如果有分析信息，也保存起来
          if (response.data.data.analysisInfo) {
            aiAnalysis.value = response.data.data.analysisInfo;
          }
        } else {
          matchResults.value = [];
          ElMessage.warning(response.data.message || "未找到匹配的物品");
        }
      } catch (error) {
        console.error("匹配失败:", error);
        ElMessage.error("匹配请求失败，请稍后重试");
        matchResults.value = [];
      } finally {
        searching.value = false;
      }
    };

    // 重置表单
    const resetForm = () => {
      itemDescription.value = "";
      searchTimeRange.value = 30;
      selectedImages.value = []; // 清空选中图片数组
      fileList.value = [];

      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }

      searched.value = false;
      matchResults.value = [];
    };

    // 查看详情
    const viewDetail = (item) => {
      const route =
        item.type === "lost" ? `/lost/${item.id}` : `/found/${item.id}`;
      window.location.href = route;
    };

    // 生成匹配结果颜色
    const getScoreColor = (score) => {
      if (score >= 90) return "#67C23A";
      if (score >= 70) return "#409EFF";
      if (score >= 50) return "#E6A23C";
      return "#F56C6C";
    };

    // 根据关键词生成模拟匹配响应
    const getMockMatchResponse = (description, timeRange) => {
      const keywords = description.toLowerCase().split(/\s+/);
      let matches = [];

      // 基础物品数据库
      const itemsDB = [
        {
          id: "l001",
          type: "lost",
          name: "黑色Nike背包",
          description: "一个黑色的Nike背包，内有笔记本电脑和课本",
          location: "图书馆三楼自习区",
          time: Date.now() - 86400000 * 2, // 2天前
          contact: "13800138001",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["黑色", "背包", "Nike", "笔记本电脑"],
        },
        {
          id: "f002",
          type: "found",
          name: "银色苹果笔记本电脑",
          description: "MacBook Pro 13寸，银色，有小米贴纸",
          location: "教学楼B区204教室",
          time: Date.now() - 86400000 * 1, // 1天前
          contact: "13800138002",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["银色", "笔记本电脑", "苹果", "MacBook"],
        },
        {
          id: "l003",
          type: "lost",
          name: "红色钱包",
          description: "红色真皮钱包，内有学生证和少量现金",
          location: "食堂二楼",
          time: Date.now() - 86400000 * 4, // 4天前
          contact: "13800138003",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["红色", "钱包", "真皮", "学生证"],
        },
        {
          id: "f004",
          type: "found",
          name: "蓝色水杯",
          description: "蓝色保温杯，有校徽logo",
          location: "篮球场附近",
          time: Date.now() - 86400000 * 6, // 6天前
          contact: "13800138004",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["蓝色", "水杯", "保温杯", "校徽"],
        },
        {
          id: "l005",
          type: "lost",
          name: "黑框眼镜",
          description: "黑色方框眼镜，近视500度",
          location: "实验楼走廊",
          time: Date.now() - 86400000 * 8, // 8天前
          contact: "13800138005",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["黑色", "眼镜", "方框", "近视"],
        },
        {
          id: "f006",
          type: "found",
          name: "白色AirPods耳机",
          description: "AirPods Pro，右耳有轻微划痕",
          location: "图书馆自习室",
          time: Date.now() - 86400000 * 15, // 15天前
          contact: "13800138006",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["白色", "耳机", "AirPods", "苹果"],
        },
        {
          id: "l007",
          type: "lost",
          name: "校园一卡通",
          description: "学号2021123456，姓名张三",
          location: "校园超市",
          time: Date.now() - 86400000 * 35, // 35天前
          contact: "13800138007",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["校园卡", "一卡通", "学生证"],
        },
        {
          id: "f008",
          type: "found",
          name: "绿色雨伞",
          description: "自动折叠伞，绿色带花纹",
          location: "行政楼门口",
          time: Date.now() - 86400000 * 45, // 45天前
          contact: "13800138008",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["绿色", "雨伞", "花纹", "折叠伞"],
        },
        {
          id: "l009",
          type: "lost",
          name: "篮球",
          description: "斯伯丁7号篮球，橙色",
          location: "体育馆",
          time: Date.now() - 86400000 * 70, // 70天前
          contact: "13800138009",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["篮球", "斯伯丁", "橙色", "7号"],
        },
        {
          id: "f010",
          type: "found",
          name: "紫色手提包",
          description: "紫色皮质手提包，内有化妆品",
          location: "女生宿舍楼下",
          time: Date.now() - 86400000 * 100, // 100天前
          contact: "13800138010",
          images: ["https://img.shetu66.com/2023/08/02/1690966649671884.png"],
          features: ["紫色", "手提包", "皮质", "化妆品"],
        },
      ];

      // 根据timeRange筛选物品
      let filteredItems = itemsDB;
      if (timeRange > 0) {
        const cutoffTime = Date.now() - 86400000 * timeRange;
        filteredItems = itemsDB.filter((item) => item.time >= cutoffTime);
      }

      // 对每个物品计算匹配分数
      filteredItems.forEach((item) => {
        // 初始分数
        let score = 60;
        let matchedKeywords = [];

        // 检查每个关键词是否匹配
        keywords.forEach((keyword) => {
          if (keyword.length <= 1) return; // 忽略单字符关键词

          // 在名称中匹配
          if (item.name.toLowerCase().includes(keyword)) {
            score += 10;
            matchedKeywords.push(keyword);
          }

          // 在描述中匹配
          if (item.description.toLowerCase().includes(keyword)) {
            score += 5;
            if (!matchedKeywords.includes(keyword)) {
              matchedKeywords.push(keyword);
            }
          }

          // 在特征标签中匹配
          item.features.forEach((feature) => {
            if (feature.toLowerCase().includes(keyword)) {
              score += 8;
              if (!matchedKeywords.includes(feature)) {
                matchedKeywords.push(feature);
              }
            }
          });
        });

        // 附加随机性以模拟真实情况
        score += Math.floor(Math.random() * 5);

        // 限制分数范围
        score = Math.min(98, Math.max(60, score));

        // 只添加分数超过70的匹配
        if (score >= 70) {
          matches.push({
            ...item,
            score,
            highlights:
              matchedKeywords.length > 0
                ? matchedKeywords
                : item.features.slice(0, 3),
          });
        }
      });

      // 按分数排序
      matches = matches.sort((a, b) => b.score - a.score);

      // 如果没有匹配，返回错误信息
      if (matches.length === 0) {
        return {
          code: 404,
          message: "没有找到匹配的物品，请尝试其他描述或扩大时间范围",
          data: { matches: [] },
        };
      }

      // 返回模拟响应
      return {
        code: 200,
        message: "匹配成功",
        data: {
          matches,
          totalCount: matches.length,
          analysisInfo: {
            keywords: keywords.filter((k) => k.length > 1),
            categories: ["电子设备", "个人物品", "学习用品"].slice(
              0,
              1 + Math.floor(Math.random() * 2)
            ),
            confidence: 75 + Math.floor(Math.random() * 15),
          },
        },
      };
    };

    return {
      uploadRef,
      lostItems,
      foundItems,
      guides,
      loadingLost,
      loadingFound,
      formatTime,
      defaultImage: DEFAULT_IMAGE,
      itemDescription,
      selectedImages,
      fileList,
      matchResults,
      searching,
      searched,
      searchTimeRange,
      aiAnalysis,
      imageUploadError,
      addAttribute,
      handleInputChange,
      handleImageChange,
      handleImageRemove,
      beforeImageUpload,
      findMatches,
      resetForm,
      viewDetail,
      getScoreColor,
      Search,
      Delete,
      Connection,
      TrendCharts,
      Plus,
      getMockMatchResponse,
      Loading,
    };
  },
};
</script>

<style scoped>
.home {
  padding: 20px 0;
}

.banner {
  margin-bottom: 40px;
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
}

.banner-content {
  height: 100%;
  width: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner-content::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
}

.banner-text {
  position: relative;
  text-align: center;
  color: white;
  z-index: 1;
}

.banner-text h2 {
  font-size: 48px;
  margin-bottom: 20px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.banner-text p {
  font-size: 24px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.latest-info {
  margin-bottom: 40px;
}

.dual-cards-container {
  display: flex;
  gap: 24px;
  margin-bottom: 20px;
}

.dual-card {
  flex: 1;
  overflow: hidden;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
}

.lost-card {
  border-top: 3px solid var(--warning-color);
}

.found-card {
  border-top: 3px solid var(--success-color);
}

.dual-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  position: relative;
  padding-left: 12px;
}

.lost-card .section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: var(--warning-color);
  border-radius: 2px;
}

.found-card .section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: var(--success-color);
  border-radius: 2px;
}

.lost-item-card,
.found-item-card {
  cursor: pointer;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  transition: all 0.3s;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  margin-bottom: 20px;
  border: 1px solid #f0f0f0;
}

.lost-item-card:hover,
.found-item-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-4px);
}

.item-image {
  width: 100%;
  height: 140px;
  object-fit: cover;
  transition: all 0.5s;
}

.lost-item-card:hover .item-image,
.found-item-card:hover .item-image {
  transform: scale(1.05);
}

.item-content {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  min-height: 100px;
}

.item-content h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-details {
  margin: 0;
}

.item-time {
  position: absolute;
  bottom: 15px;
  left: 15px;
  margin: 0;
  font-size: 12px;
  color: var(--text-light);
}

.guide-section {
  margin-bottom: 40px;
}

.guide-section h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.guide-card {
  text-align: center;
  padding: 30px 20px;
  transition: all 0.3s;
}

.guide-card:hover {
  box-shadow: var(--hover-shadow);
}

.guide-icon {
  color: var(--primary-color);
  margin-bottom: 15px;
}

.guide-card h3 {
  margin: 0 0 10px 0;
  color: var(--text-primary);
}

.guide-card p {
  margin: 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.data-overview {
  margin-bottom: 40px;
}

.overview-card {
  height: 140px;
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--hover-shadow);
}

.overview-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.overview-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.overview-icon.success {
  background-color: rgba(82, 196, 26, 0.1);
  color: var(--success-color);
}

.overview-icon.primary {
  background-color: rgba(24, 144, 255, 0.1);
  color: var(--primary-color);
}

.overview-icon.warning {
  background-color: rgba(250, 173, 20, 0.1);
  color: var(--warning-color);
}

.overview-info {
  flex: 1;
}

.overview-title {
  font-size: 16px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.overview-number {
  font-size: 28px;
  font-weight: bold;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.overview-trend {
  font-size: 14px;
  color: var(--text-light);
}

.overview-trend .up {
  color: var(--success-color);
}

.overview-trend .emphasis {
  color: var(--primary-color);
  font-weight: bold;
}

.quick-search,
.info-section,
.search-card,
.search-form,
.hot-tags,
.clickable-tag,
.side-card,
.faq-list,
.tips-list,
.faq-item,
.tip-item,
.info-tabs {
  display: none;
}

.hero-section {
  margin: 40px 0;
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  background: linear-gradient(145deg, #f7f9fc, #edf1f7);
  color: #909399;
}

.image-placeholder .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
  color: #c0c4cc;
}

.image-placeholder span {
  font-size: 14px;
}

@media (max-width: 991px) {
  .dual-cards-container {
    flex-direction: column;
  }
}

/* 智能匹配系统样式 */
.ai-matcher-card {
  margin-bottom: 30px;
  border-radius: 12px;
  border-top: 4px solid #409eff;
  overflow: hidden;
}

.ai-matcher-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ai-icon {
  color: #409eff;
  font-size: 20px;
}

.ai-tag {
  font-size: 12px;
  padding: 0 8px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
}

.matcher-content {
  padding: 10px 0;
}

.input-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.text-input {
  flex: 3;
}

.image-input {
  flex: 1;
  min-width: 200px;
}

.text-input h3,
.image-input h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.quick-attributes {
  margin-top: 15px;
}

.quick-attributes h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.attribute-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 15px 0;
}

.clickable-tag {
  cursor: pointer;
  transition: all 0.3s;
  background-color: #f4f4f5;
  border-color: #e4e7ed;
  color: #606266;
  margin-bottom: 8px;
  display: inline-block;
}

.clickable-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #d9ecff;
}

.clickable-tag:active {
  transform: translateY(0);
}

/* 添加点击波纹效果 */
.clickable-tag::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 0;
  border-radius: 100%;
  transform: scale(1, 1) translate(-50%, -50%);
  transform-origin: 50% 50%;
}

.clickable-tag:active::after {
  animation: ripple 0.4s ease-out;
}

@keyframes ripple {
  0% {
    transform: scale(0, 0) translate(-50%, -50%);
    opacity: 0.5;
  }
  100% {
    transform: scale(20, 20) translate(-50%, -50%);
    opacity: 0;
  }
}

.upload-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.action-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
  gap: 15px;
}

.filter-options {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  width: 100%;
}

.filter-label {
  font-size: 14px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.match-results {
  margin-top: 30px;
}

.results-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.match-icon {
  color: #409eff;
  font-size: 20px;
}

.results-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.match-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  overflow: hidden;
}

.match-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.match-banner {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  color: white;
}

.match-banner.lost {
  background: linear-gradient(to right, #f5a623, #f8c31c);
}

.match-banner.found {
  background: linear-gradient(to right, #13ce66, #41d885);
}

.match-type {
  font-weight: 600;
  font-size: 14px;
}

.match-score {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.score-text {
  font-size: 12px;
  margin-top: 5px;
}

.match-content {
  display: flex;
  padding: 15px;
}

.match-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 15px;
  flex-shrink: 0;
}

.match-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.match-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
}

.match-location {
  margin: 0 0 10px 0;
}

.match-highlights {
  margin: 0 0 15px 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 5px;
}

.highlights-label {
  font-size: 12px;
  color: #909399;
  margin-right: 5px;
}

.highlight-tag {
  margin: 2px;
}

.no-results {
  padding: 30px 0;
}

.no-results ul {
  text-align: left;
  margin: 10px 0;
  padding-left: 20px;
  color: #606266;
  font-size: 14px;
}

@media (max-width: 768px) {
  .input-section {
    flex-direction: column;
  }

  .match-content {
    flex-direction: column;
  }

  .match-image {
    width: 100%;
    height: 120px;
    margin-right: 0;
    margin-bottom: 15px;
  }

  .filter-options {
    flex-direction: column;
    align-items: flex-start;
  }

  .action-buttons {
    width: 100%;
    justify-content: center;
  }
}

.ai-analysis-panel {
  margin-bottom: 20px;
}

.analysis-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.analysis-item {
  display: flex;
  align-items: center;
}

.label {
  font-size: 14px;
  color: #606266;
  margin-right: 5px;
}

.keyword-tag {
  margin: 2px;
}

/* 添加加载状态样式 */
.loading-container {
  padding: 30px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-top: 20px;
}

.loading-text {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  color: #409eff;
  font-size: 16px;
}

.loading-text .el-icon {
  margin-right: 8px;
  font-size: 18px;
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 